package com.example.enjoyfood

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class LoginActivity : AppCompatActivity() {

    private lateinit var emailEditText: EditText
    private lateinit var passwordEditText: EditText
    private lateinit var loginButton: Button
    private lateinit var registerButton: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        // 调试信息
        Log.d("LoginActivity", "Layout loaded: activity_login.xml")

        emailEditText = findViewById(R.id.email_edit_text)
        passwordEditText = findViewById(R.id.password_edit_text)
        loginButton = findViewById(R.id.login_button)
        registerButton = findViewById(R.id.register_button)

        loginButton.setOnClickListener {
            login()
        }

        registerButton.setOnClickListener {
            navigateToRegister()
        }
    }

    private fun login() {
        val email = emailEditText.text.toString().trim()
        val password = passwordEditText.text.toString().trim()

        if (email.isNotEmpty() && password.isNotEmpty()) {
            if (validateCredentials(email, password)) {
                // 假设用户登录成功
                saveLoginStatus(true)
                // 跳转到主界面
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
                finish() // 结束登录活动，不会回退
            } else {
                Toast.makeText(this, "账号或密码不正确", Toast.LENGTH_SHORT).show()
            }
        } else {
            Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show()
        }
    }

    private fun validateCredentials(email: String, password: String): Boolean {
        val sharedPreferences = getSharedPreferences("user_profile", MODE_PRIVATE)
        val savedNickname = sharedPreferences.getString("nickname", "")
        val savedPassword = sharedPreferences.getString("password", "")

        return email == savedNickname && password == savedPassword
    }

    private fun navigateToRegister() {
        // 跳转到注册界面
        val intent = Intent(this, RegisterActivity::class.java)
        startActivity(intent)
    }

    private fun saveLoginStatus(isLoggedIn: Boolean) {
        val sharedPreferences = getSharedPreferences("app_prefs", MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.putBoolean("is_logged_in", isLoggedIn)
        editor.apply()
    }
}